package cn.jkgly.auth.controller;

import cn.jkgly.utils.AuthUtil;
import cn.jkgly.websocket.server.SocketServer;
import cn.jkgly.wxUser.entity.Result;
import cn.jkgly.wxUser.entity.WxRelateAccount;
import cn.jkgly.wxUser.entity.WxUser;
import cn.jkgly.wxUser.service.IWxRelateAccountService;
import cn.jkgly.wxUser.service.IWxUserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 授权相关业务
 */

@RequestMapping("/auth")
@Controller
public class AuthController {
    @Autowired
    IWxUserService wxUserService;
    @Autowired
    IWxRelateAccountService wxRelateAccountService;
    private static final Logger logger = LoggerFactory.getLogger(SocketServer.class);

    /**
     * 返回手机导航页面
     * @return
     */
    @RequestMapping("/mobileNavigation")
    public String mobileNavigation(HttpServletRequest request) {
        //todo:获取个人基本信息访问
        
        return "/mobileNavigation";
    }

    /**
     * 现在是展示微信二维码，等待扫码，然后跳转到bi.jkgly.cn展示数据
     * @return
     */
    @RequestMapping("/pcNavigation")
    public String pcNavigation() {
        return "/PcNavigation";
    }


    /**
     * 2、接收微信用户信息，根据UUID推送网址，用户名和密码等消息，进行跳转如考试，院长查询
     *
     * @return
     */
    @PostMapping("/getAuthorization")
    @ResponseBody
    public Result<?> getAuthorization(@RequestBody Map<String, Object> map) {
        System.out.println(map);
        QueryWrapper<WxUser> queryWrapper = new QueryWrapper<WxUser>();
        queryWrapper.eq("openid", map.get("openid").toString());
        WxUser user = wxUserService.getOne(queryWrapper);
        if (user == null) {
            SocketServer.sendMessage("未找到微信用户", map.get("clientid").toString());
            return Result.error("未找到微信用户");

        } else {
            if (!user.getAuthorization().contains("PC登录")) {
                SocketServer.sendMessage("用户未获取扫码登录授权", map.get("clientid").toString());
                return Result.error("用户未获取扫码登录授权");
            } else {
                WxRelateAccount whereUser = new WxRelateAccount();
                whereUser.setAppName(map.get("appName").toString());
                whereUser.setOpenid(map.get("openid").toString());
                QueryWrapper<WxRelateAccount> queryWrapper2 = new QueryWrapper<WxRelateAccount>(whereUser);
                WxRelateAccount relateAccount = wxRelateAccountService.getOne(queryWrapper2);
                if (relateAccount == null) {
                    SocketServer.sendMessage("用户未设置关联账户", map.get("clientid").toString());
                    return Result.error("用户未设置关联账户");
                } else {
                    String login_info = "success" + "|" +
                            relateAccount.getLoginUrl() + "|" +
                            relateAccount.getTargetUrl() + "|" +
                            relateAccount.getAppAccount() + "|" +
                            relateAccount.getAppPassword();
                    if (SocketServer.sendMessage(login_info, map.get("clientid").toString())) {
                        return Result.ok("授权成功");
                    } else {
                        return Result.error("发送授权失败，请刷新电脑页面");
                    }
                }
            }
        }
    }


    Map<String, String> codeMap = new HashMap<>();

    /**
     * 1、从微信回调中获取用户信息，下一步展示手机授权页面；
     * 微信接口存在微信多次访问回调地址的问题，解决办法：
     * 1、使用codeMap判断code是否已经使用；
     * 2、方法使用 synchronized 关键字；
     * @param
     * @param
     * @return
     */
    @RequestMapping("/mobileAuthorization")
    public synchronized String mobileAuthorization(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        logger.info("======收到回调请求，开始业务操作=======");
        //1.appid申请code
        String code = req.getParameter("code");
        if (code == null) {
            logger.error("code null");
            return "code null";
        }
        if (codeMap.containsKey(code)) {
            logger.error("code already push" + code);
            return "code already push" + code;
        }
        codeMap.put(code, "");
        logger.info("开始正常业务：" + code);
        //1.附加appid申请code
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" + AuthUtil.APPID +
                "&secret=" + AuthUtil.APPSECRET +
                "&code=" + code +
                "&grant_type=authorization_code";
        JSONObject jsonObject = AuthUtil.doGetJson(url);

        String openid = jsonObject.getString("openid");
        String token = jsonObject.getString("access_token");

//token过期，刷新数据
//        String tokenRefreshUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token" +
//                "?appid=APPID" +
//                "&grant_type=refresh_token" +
//                "&refresh_token=REFRESH_TOKEN";

        String infoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=" + token +
                "&openid=" + openid +
                "&lang=zh_CN";
        JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
        String appName = req.getParameter("appName");
        String clientid = req.getParameter("clientid");
        String state = req.getParameter("state");
        logger.info(userInfo.toJSONString());
        logger.info("openid:" + openid + "|state:" + state + "|clientid:" + clientid + "|appName:" + appName);
        logger.info("=======回调业务完成=======");
        logger.info("===开始鉴权==openid:" + openid + "|state:" + state + "|clientid:" + clientid + "|appName:" + appName + "====");

        req.setAttribute("info", userInfo);
        req.setAttribute("clientid", clientid);
        req.setAttribute("appName", appName);
        return "/wxIndex";

    }
}
